﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MvcBlog.Common.Models
{
    public class EntryDataAccess
    {

        private MvcBlogEntities db;

        public EntryDataAccess(Object db_access)
        {
            db = (MvcBlogEntities)db_access;
        }


        //hier die abfrage-methoden
        public IQueryable<Entry> getEntries(int skip, int take)
         {
             try
             {
                 var res = db.Entry
                     .OrderByDescending(q => q.CreateDate)
                     .Skip(skip).Take(take);

                 return res;
             }
             catch
             {
                 return null;
             }

         }

         public Entry getEntryByID(int id)
         {
             var res = db.Entry
            .Include("User")
            .Where(e => e.Entry_ID == id);

             try
             {
                 return res.First();
             }
             catch
             {
                 return null;
             }
         }

         public Entry insertEntry(Entry e, User user)
         {
             try
             {
                 e.CreateDate = DateTime.Now;

                 //eingeloggten User prüfen, Berechtigt?
                 //int User_ID = 1;

                 //neuen eintrag mit autor verknüpfen -> eintrag wird implizit gespeichert
                 e.User = db.User.Single(q => q.User_ID == user.User_ID);

                 //db.Question.AddObject(question);
                 db.SaveChanges();

                 return e;
             }
             catch (Exception)
             {
                 return null;
             }
         }


    }
}
